package com.pig.service;

import com.pig.pojo.ImageVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Service
public class FileUploadServiceImpl implements FileService {
    //定义文件存储的根目录
    //@Value("${image.filDir}")
    private String fileLocalDir = "/usr/local/pqmc/recipesimages/";
    //@Value("${image.urlPath}")
    private String urlPath = "http://159.75.44.225:8757";
    private static Set<String> typeSet = new HashSet<>();

    static {
        typeSet.add(".jpg");
        typeSet.add(".png");
        typeSet.add(".gif");
    }
    @Override
    public ImageVo upload(MultipartFile myFile, Integer categoryId) {
        String imageName = myFile.getOriginalFilename().toLowerCase();
        System.out.println("-----------"+imageName);
        int index = imageName.lastIndexOf(".");
        String imageType = imageName.substring(index);
        if (!typeSet.contains(imageType))
        {
            return ImageVo.fail(); //结束任务
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(myFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width==0||height==0)
            {
                return ImageVo.fail();
            }
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDirPath =  fileLocalDir+ dateDir;
            File dirFile = new File(fileDirPath);
            if(!dirFile.exists()){
                dirFile.mkdirs();

            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String uuidName = uuid+imageType;
            File realFile = new File(fileDirPath+uuidName);
            myFile.transferTo(realFile);

            //网络访问虚拟地址:   http://image.pqmc.com\2020\12\02\a.jpg
            String url =  urlPath + dateDir + uuidName;

            return ImageVo.success(url, width,height);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
